package org.example.quartz.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.quartz.service.UtilService;
import org.example.quartz.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController("jdbcUtilControllerSlave1")
@RequestMapping(path = "/GSYY/JdbcUtilController")
public class JdbcUtilController {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value(value = "${spring.datasource.databaseType}")
    private String databaseType;
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    //orgService
    UtilService utilService = SpringUtil.getBean(UtilService.class);

    /**
     * 读取yy信息
     *
     * @param
     * @return
     */
    @PostMapping("/getType")
    public Result getType() {
        try {
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList("SELECT * FROM " + utilService.getGSYY() + ".\"SJK_TYPE\"");
            return Result.success(mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param param
     * @return
     */
    @PostMapping("/addJdbc")
    public Result addJdbc(@RequestBody Map<String, Object> param) {
        DataSource ds = new SimpleDataSource(jdbcUrl, username, password);
        try (Session session = Session.create(ds)) {
            if ("oracle".equals(databaseType)) {
                Entity entity = Entity.create("jdbc_util");
                entity.set("ID", String.valueOf(IdUtil.getSnowflakeNextId()).substring(11));
                entity.set("DELETE_STATE", 0);
                for (Map.Entry<String, Object> stringObjectEntry : param.entrySet()) {
                    if ("typesource".equals(stringObjectEntry.getKey())) {
                        entity.set("type", stringObjectEntry.getValue());
                    } else {
                        entity.set(stringObjectEntry.getKey(), stringObjectEntry.getValue());
                    }
                }
                session.insert(entity);
                return Result.success("新增成功");
            } else if ("dm".equals(databaseType)) {
                String insertSql = "INSERT INTO " + utilService.getGSYY() + ".jdbc_util ( ID,TYPE, CODE, NAME, DRIVERCLASS, DRIVERNAME, URL, USERNAME, PASSWORD )\n" +
                        "VALUES\n" +
                        "\t( \n" +
                        "\t'" + String.valueOf(IdUtil.getSnowflakeNextId()).substring(11) + "', \n" +
                        "\t'" + param.get("typesource") + "', \n" +
                        "\t'" + param.get("code") + "', \n" +
                        "\t'" + param.get("name") + "', \n" +
                        "\t'" + param.get("driverclass") + "', \n" +
                        "\t'" + param.get("drivername") + "', \n" +
                        "\t'" + param.get("url") + "', \n" +
                        "\t'" + param.get("username") + "', \n" +
                        "\t'" + param.get("password") + "' \n" +
                        "\t)";
                jdbcTemplate.update(insertSql);
                return Result.success("新增成功");
            } else {
                String insertSql = "INSERT INTO " + utilService.getGSYY() + ".jdbc_util (ID, TYPE, CODE, NAME, DRIVERCLASS, DRIVERNAME, URL, USERNAME, PASSWORD )\n" +
                        "VALUES\n" +
                        "\t( \n" +
                        "\t'" + String.valueOf(IdUtil.getSnowflakeNextId()).substring(11) + "', \n" +
                        "\t'" + param.get("typesource") + "', \n" +
                        "\t'" + param.get("code") + "', \n" +
                        "\t'" + param.get("name") + "', \n" +
                        "\t'" + param.get("driverclass") + "', \n" +
                        "\t'" + param.get("drivername") + "', \n" +
                        "\t'" + param.get("url") + "', \n" +
                        "\t'" + param.get("username") + "', \n" +
                        "\t'" + param.get("password") + "' \n" +
                        "\t)";
                jdbcTemplate.update(insertSql);
                return Result.success("新增成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 修改
     *
     * @param param
     * @return
     */
    @PostMapping("/updateJdbc")
    public Result updateJdbc(@RequestBody Map<String, Object> param) {
        DataSource ds = new SimpleDataSource(jdbcUrl, username, password);
        try (Session session = Session.create(ds)) {
            if ("oracle".equals(databaseType)) {
                Entity entity = Entity.create("jdbc_util");
                for (Map.Entry<String, Object> stringObjectEntry : param.entrySet()) {
                    if ("typesource".equals(stringObjectEntry.getKey())) {
                        entity.set("type", stringObjectEntry.getValue());
                    } else {
                        entity.set(stringObjectEntry.getKey(), stringObjectEntry.getValue());
                    }
                }
                session.update(entity, Entity.create("jdbc_util").set("id", param.get("id")));
                return Result.success("修改成功");
            } else if ("dm".equals(databaseType)) {
                String updateSql = "UPDATE " + utilService.getGSYY() + ".jdbc_util\n" +
                        "SET type = '" + param.get("typesource") + "',\n" +
                        "code = '" + param.get("code") + "',\n" +
                        "name = '" + param.get("name") + "',\n" +
                        "driverClass = '" + param.get("driverclass") + "',\n" +
                        "driverName = '" + param.get("drivername") + "',\n" +
                        "url = '" + param.get("url") + "',\n" +
                        "username = '" + param.get("username") + "',\n" +
                        "password = '" + param.get("password") + "' \n" +
                        "WHERE id = '" + param.get("id") + "'";
                jdbcTemplate.update(updateSql);
                return Result.success("修改成功");
            } else {
                String updateSql = "UPDATE " + utilService.getGSYY() + ".jdbc_util\n" +
                        "SET type = '" + param.get("typesource") + "',\n" +
                        "code = '" + param.get("code") + "',\n" +
                        "name = '" + param.get("name") + "',\n" +
                        "driverClass = '" + param.get("driverclass") + "',\n" +
                        "driverName = '" + param.get("drivername") + "',\n" +
                        "url = '" + param.get("url") + "',\n" +
                        "username = '" + param.get("username") + "',\n" +
                        "password = '" + param.get("password") + "' \n" +
                        "WHERE id = '" + param.get("id") + "'";
                jdbcTemplate.update(updateSql);
                return Result.success("修改成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteJdbc")
    public Result deleteJdbc(@RequestParam("id") String id) {
        try {
            String updateSql = "UPDATE " + utilService.getGSYY() + ".jdbc_util \n" +
                    "SET  delete_state = '1'\n" +
                    "WHERE\n" +
                    "\tid = '" + id + "'";
            int update = jdbcTemplate.update(updateSql);
            String msg = "";
            if (update > 0) {
                msg = "删除成功";
                return Result.success(msg);
            } else {
                msg = "删除失败";
                return Result.fail(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 查询列表
     *
     * @param param
     * @return
     */
    @PostMapping("/getList")
    public Result getList(@RequestBody Map<String, Object> param) {
        try {
            String condition = "";
            // 拼接条件
//            if (!ObjectUtils.isEmpty(param.get("name"))) {
//                condition += " and ";
//            }else if(!ObjectUtils.isEmpty(param.get("name"))){
//                condition += " and ";
//            }
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from " + utilService.getGSYY() + ".jdbc_util where delete_state = 0 " + condition);
            return Result.success(mapList);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 查询单条
     *
     * @param id
     * @return
     */
    @PostMapping("/getById")
    public Result getById(@RequestParam("id") Integer id) {
        try {
            String sql = "select * from " + utilService.getGSYY() + ".jdbc_util where delete_state = 0 and id = '" + id + "'";
            Map<String, Object> map = jdbcTemplate.queryForMap(sql);
            return Result.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


}
